package com.yanqu.road.server.cmd.activity.entername;

import com.yanqu.road.entity.log.LogEnterNameActivityAdd;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.cross3.activity.EnterNameProto;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.manger.activity.entername.EnterNameActivityMgr;
import com.yanqu.road.server.manger.activity.entername.EnterNameCache;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.protocol.Protocol;
import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Cmd(code = Protocol.S_ENTER_NAME_NAME_SYNC_FROM_CHANNEL, desc = "报名结果下发")
public class EnterNameAddFromChannelCmd implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage yanQuMessage) throws Exception {

        EnterNameProto.ChannelEnterNameBatchSyncMsg syncMsg = EnterNameProto.ChannelEnterNameBatchSyncMsg.parseFrom(yanQuMessage.getBytes());

        Map<Long, EnterNameCache> cacheMap = new ConcurrentHashMap<>();
        List<Long> userList = new ArrayList<>();
        for (EnterNameProto.ChannelEnterNameMsg enterNameMsg : syncMsg.getNameList()) {
            EnterNameCache cache = new EnterNameCache();
            cache.setUserId(enterNameMsg.getUserId());
            cache.setZoneId(enterNameMsg.getZoneId());
            cacheMap.put(cache.getUserId(), cache);
            userList.add(cache.getUserId());
        }

        EnterNameActivityMgr.cacheEnterName(syncMsg.getActivityId(), cacheMap);
        EnterNameActivityMgr.getLogger().info("enter name cache activityId {}, user size {}", syncMsg.getActivityId(), cacheMap.size());
        EnterNameActivityMgr.notifyName(syncMsg.getActivityId(), userList);

        //报名日志
        for (Map.Entry<Long, EnterNameCache> cacheEntry : cacheMap.entrySet()) {
            EnterNameCache nameCache = cacheEntry.getValue();
            UserInfo userInfo = UserMgr.getUserInfo(nameCache.getUserId());
            if(userInfo != null) {
                AutoLogMgr.add(new LogEnterNameActivityAdd(
                        syncMsg.getActivityId(),
                        nameCache.getUserId(),
                        userInfo.getIpLocation(),
                        nameCache.getZoneId(),
                        1));
            }
        }
    }
}
